package com.yrd.fssync.core;

import java.io.File;
import java.util.ArrayDeque;
import java.util.Deque;

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.lang3.StringUtils;

/**
 *  
 */
public class FileSystemListener extends FileAlterationListenerAdaptor {
	Context context;
	String localBase;
	File localBaseDir;
	SyncEngineMap syncEngineMap;
	
	public FileSystemListener(Context context, String localBase) {
		this.context = context;
		this.localBase = localBase;
		this.localBaseDir = new File(this.localBase);
	}

	public String getLocalBase() {
		return localBase;
	}

	
	public SyncEngineMap getSyncEngineMap() {
		return syncEngineMap;
	}

	public void setSyncEngineMap(SyncEngineMap syncEngineMap) {
		this.syncEngineMap = syncEngineMap;
	}

	// 文件夹创建
	@Override
	public void onDirectoryCreate(File directory) {
		sendMsg(directory.getAbsolutePath() + " directory Create");
		String rPath = Utils.relativeLocalPath(localBaseDir,directory);
		SyncRequest request = new SyncRequest(directory,rPath,SyncRequest.FILETYPE_DIR,SyncRequest.DISPOSE_OVERWRITE);
		syncEngineMap.post(request);
	}

	// 文件夹改变
	@Override
	public void onDirectoryChange(File directory) {
		sendMsg(directory.getAbsolutePath() + " directory Change");
	}

	// 文件夹删除
	@Override
	public void onDirectoryDelete(File directory) {
		sendMsg(directory.getAbsolutePath() + " directory Delete");
		String rPath = Utils.relativeLocalPath(localBaseDir,directory);
		SyncRequest request = new SyncRequest(directory,rPath,SyncRequest.FILETYPE_DIR,SyncRequest.DISPOSE_DELETE);
		syncEngineMap.post(request);
	}

	// 文件创建
	@Override
	public void onFileCreate(File file) {
		sendMsg(file.getAbsolutePath() + " file Create");
		String rPath = Utils.relativeLocalPath(localBaseDir,file);
		SyncRequest request = new SyncRequest(file,rPath,SyncRequest.FILETYPE_FILE,SyncRequest.DISPOSE_OVERWRITE);
		syncEngineMap.post(request);
	}

	// 文件改变
	@Override
	public void onFileChange(File file) {
		sendMsg(file.getAbsolutePath() + " file Change");
		String rPath = Utils.relativeLocalPath(localBaseDir,file);
		SyncRequest request = new SyncRequest(file,rPath,SyncRequest.FILETYPE_FILE, SyncRequest.DISPOSE_OVERWRITE);
		syncEngineMap.post(request);
	}

	// 文件删除
	@Override
	public void onFileDelete(File file) {
		sendMsg(file.getAbsolutePath() + " file Delete");
		String rPath = Utils.relativeLocalPath(localBaseDir,file);
		SyncRequest request = new SyncRequest(file,rPath,SyncRequest.FILETYPE_FILE,SyncRequest.DISPOSE_DELETE);
		syncEngineMap.post(request);
	}

	private void sendMsg(String message){
		Utils.printfln(message);
		context.getHttpEngine().sendMessage(message);
	}
}
